﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using P2PLib.Common.DataModel;
using System.Net;

namespace P2PLib.Common.Command
{
    public class CSClientInfoCommand:CSCommandBase
    {
        private int size;
        private List<ClientInfo> clients;

        public int Size
        {
            set
            {
                size = value;
            }
            get
            {
                return this.size;
            }
        }

        public List<ClientInfo> Clients
        {
            set
            {
                this.clients = value;
            }
            get
            {
                return this.clients;
            }
        }

        public CSClientInfoCommand()
            : base(CSCommandType.ClientInfo)
        {
            this.size = 0;
            this.clients = new List<ClientInfo>();
        }

        public CSClientInfoCommand(int s,List<ClientInfo> list)
            : base(CSCommandType.ClientInfo)
        {
            this.clients = list;
            this.size = s;
        }

        public override void WriteToStream(System.IO.Stream stream)
        {
            byte[] buffer = new byte[4];
            buffer = BitConverter.GetBytes(size);
            stream.Write(buffer,0,4);
            foreach (ClientInfo c in clients) {
                buffer = BitConverter.GetBytes(c.Port);
                stream.Write(buffer, 0, 4);
                buffer = Encoding.ASCII.GetBytes(c.IP.ToString());
                stream.Write(BitConverter.GetBytes(buffer.Length), 0, 4);
                stream.Write(buffer, 0, buffer.Length);
            }
        }

        public override void ReadFromStream(System.IO.Stream stream)
        {
            byte[] buffer = new byte[4];
            stream.Read(buffer, 0, 4);
            this.size = BitConverter.ToInt32(buffer, 0);
            this.clients = new List<ClientInfo>();
            for (int i = 0; i < this.size; i++) {
                ClientInfo c = new ClientInfo("127.0.0.1", 1234);
                buffer = new byte[4];
                stream.Read(buffer, 0, 4);
                c.Port = BitConverter.ToInt32(buffer, 0);
                stream.Read(buffer, 0, 4);
                int ipSize = BitConverter.ToInt32(buffer, 0);
                buffer = new byte[ipSize];
                stream.Read(buffer, 0, ipSize);
                c.IP = IPAddress.Parse(Encoding.ASCII.GetString(buffer));
                this.clients.Add(c);
            }
        }
    }
}
